(function() {
	angular
		.module('ydApp.clinic')
		.config(function($stateProvider) {
			$stateProvider.state('clinic-list', {
				url: '/clinic-list',
				controller: "clinicListCtrl",
				templateUrl: 'views/clinic/clinic-list.html'
			});
			$stateProvider.state('clinic-detail', {
				url: '/clinic-detail',
				controller: "clinicDetailCtrl",
				templateUrl: 'views/clinic/clinic-detail.html'
			});
		})
		.controller("clinicListCtrl", clinicListCtrl)
		.controller("clinicDetailCtrl", clinicDetailCtrl);

	function clinicListCtrl($scope, xhr, $state) {
		var vm = $scope.vm = {};

		$scope.downloadImg = function(img) {
            return config.api + "HealthInquiry" + img;
        }

		vm.condition = {
			pageIndex: -1,
			sorter: 'intelligent',
			branchId: null
		}

		vm.search = function() {
			xhr.get('HealthInquiry/com/clinic/findByNow', vm.condition).then(function(result) {
				vm.data = result.data;
			});
		};

		xhr.get("HealthInquiry/com/branch/findByCondition", {
			pageIndex: 0,
			pageSize: 100
		}).then(function(res) {
			if (res.successful) {
				vm.departs = res.data;
			}
		})

		vm.departSearch = function(branchId) {
			if (branchId) {
				vm.condition.branchId = branchId;
			} else {
				vm.condition.branchId = null;
			}

			vm.menu(1);
			vm.doRefresh();
		}

		vm.sortSearch = function(sorter) {
			vm.condition.sorter = sorter;
			vm.menu(2);
			vm.doRefresh();
		}

		// vm.search();

		vm.flag = 0;
		vm.data = [];

		vm.menu = function(id) {
			if (vm.flag == id) {
				vm.flag = 0;
			} else {
				vm.flag = id;
			}
		}

		vm.doRefresh = function() {
			vm.data = [];
			vm.condition.pageIndex = 0;
			vm.nodata = false;
			vm.load().finally(function() {
				$scope.$broadcast('scroll.refreshComplete');
			});
		}
		vm.loadMore = function() {
			vm.condition.pageIndex++;
			vm.load().then(function() {
				$scope.$broadcast('scroll.infiniteScrollComplete');
			});
		}
		vm.load = function() {
			return xhr.get("HealthInquiry/com/clinic/findByNow", vm.condition).then(function(result) {
				if (result.data.length == 0) {
					vm.nodata = true;
				}
				vm.data = vm.data.concat(result.data);
			})
		}
		vm.toDetail = function(docId) {
			$state.go("doc-detail", {
				docId: docId
			});
		}
	}

	function clinicDetailCtrl($scope) {
		var vm = $scope.vm = {};
	}
})();